VER=${VER}
if [ "$VER" = "" ]; then
    VER=`git log -1 --pretty=format:%cd-%h --date=short`
    if [ $? != 0 ]; then
      echo "must provide ver or in a git repository"
      exit -1
    fi
fi
APPNAME=${APP:-lottery}
#kubernetes replication controller name
RCNAME=$APPNAME
#kubernetes service name
SVCNAME=$APPNAME
#export servie port
SVCPORT=${SVCPORT:-49999}
#export other port
EPORT=${EPORT:-''}
NUM=${NUM:-1}
DEPLOY=${DEPLOY:-TRUE}
RUN_PROFILE=${RUN_PROFILE:-debug}
echo use name:$APPNAME version:$VER 
LOG_PATH=${LOG_PATH:-/var/log/lottery}
#build port string
PORTSTR='{"containerPort":'$SVCPORT'},'
for p in $EPORT; do
    PORTSTR+='{"containerPort":'$p'},'
done

UUID=${UUID}
if [ "$UUID" = "" ]; then
    UUID=$APPNAME
fi

IMAGE=${IMAGE}
if [ "$IMAGE" = "" ];  then
    IMAGE="xl.reg.com:5000/$APPNAME:$VER"
fi

LB_IP=${LB_IP}
if [ "$LB_IP" = "" ]; then
    LB_IP=192.168.1.169
fi

PORTSTR+='{"containerPort":'22'}'

NAMESPACE=${NAMESPACE}
if [ "$NAMESPACE" = "" ];  then
    NAMESPACE="default"
fi

NODEPORT=${NODEPORT}
if [ "$NODEPORT" = "" ]; then
    NODEPORT=$SVCPORT
fi

#build replication controller string
RCCreateStr=$(cat <<EOF
apiVersion: v1
kind: ReplicationController
metadata:
  name: $RCNAME
spec:
  replicas: $NUM
  selector:
    app: $APPNAME
  template:
    metadata:
      labels:
        app: $APPNAME
    spec:
      containers:
      - name: $APPNAME
        image: $IMAGE
        ports: [$PORTSTR]
        imagePullPolicy: Always
        env:
        - name: RUN_PROFILE
          value: $RUN_PROFILE
        volumeMounts:
        - name: logpath
          mountPath: /usr/local/apache-tomcat-8.0.26/logs
      volumes:
      - name: logpath
        hostPath:
          path: $LOG_PATH
EOF
)

echo -e "$RCCreateStr"

#build service string
SVCCreateStr=$(cat <<EOF
apiVersion: v1
kind: Service
metadata:
  name: $SVCNAME
  labels:
    uuid: ${UUID}
spec:
  ports:
  - port: $SVCPORT
    targetPort: 8080
    protocol: TCP
    nodePort: $NODEPORT
  type: LoadBalancer
  loadBalancerIP: $LB_IP
  selector:
    app: $APPNAME
EOF
)

echo -e "$SVCCreateStr"

recreateRC() {
    kubectl delete rc $RCNAME --namespace=$NAMESPACE
    echo -e "$RCCreateStr" | kubectl create --namespace=$NAMESPACE -f -
}

recreateSVC() {
    kubectl delete svc $SVCNAME --namespace=$NAMESPACE
    echo -e "$SVCCreateStr" | kubectl create --namespace=$NAMESPACE -f -
}
if [ "$DEPLOY" = "TRUE" ] ;then
    recreateRC
    recreateSVC
fi
